package com.easylinkin.security.config;

import com.easylinkin.sm.constant.LogConstant.Module;
import com.easylinkin.sm.entity.Department;
import com.easylinkin.sm.entity.Log;
import com.easylinkin.sm.entity.User;
import com.easylinkin.sm.service.DepartmentService;
import com.easylinkin.sm.service.LogService;
import com.easylinkin.sm.service.UserService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;
import site.morn.framework.context.AccountContext;

/**
 * 登出成功处理
 *
 * @author TianGanLin
 * @since 1.0.0, 2019/9/12
 */
@Component
public class RestLogoutSuccessHandler implements LogoutSuccessHandler {

  @Autowired
  private UserService userService;

  @Autowired
  private LogService logService;

  @Autowired
  private DepartmentService departmentService;

  @Override
  public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response,
      Authentication authentication) {

    // 记录日志
    String username =  authentication.getName();
    User user = userService.findByUsername(username);
    Department department = departmentService.get(user.getDepartmentId());

    Log log = new Log();
    log.setModuleId(Long.parseLong(Module.LOGIN));
    log.setIp(request.getRemoteAddr());
    log.setContent("用户登出");
    log.setStatus(true);
    log.setDisplay(true);
    log.setCreator(username);
    log.setModifier(username);
    log.setCustomerId(department.getCustomerId());
    logService.add(log);

    // 清空登录缓存
    AccountContext.cacheGroup().clearKey(authentication.getName());
  }
}
